package com.qyer.search.sort;

import com.google.common.collect.Lists;
import com.qyer.search.cache.mutable.MutableCaches;
import com.qyer.search.exception.SearchException;
import com.qyer.search.model.SearchParameterEntity;
import com.qyer.search.model.lastminute.SimpleVSKUExtra;
import com.qyer.search.model.lastminute.VSKU;
import com.qyer.search.model.result.SearchEntity;
import com.qyer.search.utils.ListUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Created by tangzheng on 16/8/19.
 */
public class VSalesTimSorterNoMarket2 implements SearchSorter{
  private SearchParameterEntity sp;
  private SearchEntity searchEntity;
  private int orderDirection ;
  private int from;
  private int to;

  public VSalesTimSorterNoMarket2(SearchParameterEntity sp, SearchEntity searchEntity, int orderDirection, int from, int to) {
    this.sp = sp;
    this.searchEntity = searchEntity;
    this.orderDirection = orderDirection;
    this.from = from;
    this.to = to;

  }

  @Override public List<SearchEntity> sort() throws SearchException {
    long t1 = System.currentTimeMillis();
    ///////////////////////
    if(searchEntity == null){
      return new ArrayList<>();
    }
    if(searchEntity.getPackageSize() == 0) {
      //System.out.println("PackageSize为0");
      return new ArrayList<>();
    }

    Map<Integer,Long> sales = MutableCaches.getInstance().SALES.getCacheContent();
    List<SearchEntity> searchEntities = new ArrayList<>(1);
    List<VSKU> skus;
    skus = searchEntity.getSkus();
    int size = skus.size();
    VSKU sku;
    int id;
    long sale;
    for(int i = 0; i < size; i++){
      sku = skus.get(i);
      id = sku.getId();
      if(sales.containsKey(id)) {
        sale = sales.get(id);
        sku.setSale(sale);
      }else {
        if(orderDirection == 1){
          sku.setSale(Long.MAX_VALUE);
        }else {
          sku.setSale(Long.MIN_VALUE);
        }
      }
    }
    if(orderDirection == 0){
      Collections.sort(skus, new Comparator<VSKU>() {
        @Override public int compare(VSKU o1, VSKU o2) {
          return (int) (o1.getSale() - o2.getSale());
        }
      });
    }else if(orderDirection == 1){
      Collections.sort(skus, new Comparator<VSKU>() {
        @Override public int compare(VSKU o1, VSKU o2) {
          return (int)(o2.getSale()- o1.getSale());
        }
      });
    }
    searchEntity.resizeSKUs(from, to);
    searchEntities.add(searchEntity);
    return searchEntities;
  }
}
